import axios from 'axios'
import storage from '../utils/storage'
import { message} from "antd";
import memoryUtills from '../utils/memoryUtils'


// const BASE_URL = 'http://192.168.0.113:8081/'
const BASE_URL = ''

const http = axios.create({
    timeout: 1000 * 30,
    baseURL: BASE_URL,
    withCredentials: true,
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    }
})
/**
 * 请求拦截
 */
http.interceptors.request.use(config => {
    config.headers['token'] = storage.getToken('token') // 请求头带上token
    return config
}, error => {
    return Promise.reject(error)
})

/**
 * 响应拦截
 */
http.interceptors.response.use(response => {
    if (response.data && response.data.code === 401) { // 401, token失效
        // clearLoginInfo()
        storage.removeUser()
        memoryUtills.user = ''
        window.location.href = '/login';
    }
    return response
}, error => {
    return Promise.reject(error)
})

http.httpRequest = (url, data={}, type='GET') => {
    return new Promise((resolve, reject) => {
        let promise
        if (type === 'GET') {
            promise = http.get(url, {
                params: data
            })
        } else if(type === 'DELETE') {
            promise = http.delete(url,data)
        } else {
            promise = http.post(url, data)
        }
        promise.then(response => {
            resolve(response)
        }).catch(error => {
            message.error('请求出错' + error)
        })
    })
}
export default http